<!-- treeNode.vue -->
<template>
	<!-- 树形结构组件 -->
	<view>
		<view class="item--list" v-for="(item, index) in list" :key="index">
			<view class="item--title" hover-class="tree__hover-class" @click="selectNode(item)">
				<view>{{ item.Name }}</view>
				<view v-if="item.children && item.children.length" class="open__and--close"
					@click.stop="handleOpenClose(item, index)">
					{{ item.isOpen?'收起':'展开'}}
				</view>
			</view>
			<!-- 使用组件本身渲染子项 -->
			<view v-if="item.isOpen && item.children && item.children.length" class="">
				<treeItem :list="item.children" @change="selectNode"></treeItem>
			</view>
		</view>
	</view>
</template>

<script>
	// 引入当前组件
	import treeItem from "@/components/treeNode.vue"
	export default {
		name: 'treeItem',
		components: {
			treeItem
		},
		// 接收列表数据
		props: {
			list: {
				item: Array,
				default: () => []
			}
		},
		methods: {
			// 选中
			selectNode(item) {
				this.$emit('change', item)
			},
			// 处理展开或收起
			handleOpenClose(item, index) {
				// 如果不存在isOpen属性就添加该属性。
				if (!item.hasOwnProperty('isOpen')) {
					item.isOpen = false
				}
				item.isOpen = !item.isOpen
				this.$forceUpdate()
			}
		}
	}
</script>

<style scoped>
	.item--list {
		padding-left: 25rpx;
	}

	.item--title {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		border-bottom: 1rpx solid #f7f7f7;
		padding: 25rpx;
	}

	.open__and--close {
		margin-left: auto;
		font-size: 24rpx;
	}

	.tree__hover-class {
		background-color: #f7f7f7;
	}
</style>